<template>
	<view class="page__content">
		<z-paging ref="paging" :auto="false" :default-page-size="20" v-model="filterResult" @query="getSearchList">
			<template #top>
				<up-navbar :fixed="false" :title="pageParam.name +'筛选'" :autoBack="true" :safeAreaInsetTop="true"
					leftIconColor="#fff">
				</up-navbar>

				<view class="SearchBox" v-if="showSearch">
					<up-search :showAction="true" v-model="filterData[searchKey]" @search="search" @custom="SearchOrAdd"
						shape="square" :actionText="AllowAddEdit ? '+' :'查询'"
						:actionStyle="{color:'#fff',fontSize: AllowAddEdit ? '40px' : '16px'}"
						:animation="false"></up-search>
				</view>
				<view style="padding:10px;border-bottom: 1px solid #ebebeb;" v-if="parentValue">
					<up-icon name="arrow-down" :label="typeName" labelPos="left"
						style="display: flex;justify-content: center;" @click="openChooseType"></up-icon>
				</view>
			</template>


			<view class="page__content__main">
				<up-cell v-for="(item, index) in filterResult" :key="index" :title="item[displayValue]" size="large"
					:clickable="true" @click="ChoiceCell(item)" :titleStyle="{fontSize:'28rpx'}">
				</up-cell>
			</view>

		</z-paging>
		<next-tree :selectParent="true" :checkStrictly="true" funcMode="checkbox" ref="nextTreeAsyncRef"
			:expandedKeys="expandNodes" :treeData="treeData" :themeColor="treeThemeColor" :cancelColor="treeThemeColor"
			:titleColor="treeThemeColor" @confirm="onTreeConfirm"></next-tree>

	</view>
</template>

<script setup lang="ts">
	import { ref, onMounted, onUnmounted, computed, reactive } from 'vue';
	import { onLoad, onShow, onUnload } from "@dcloudio/uni-app";
	import useRequestQueue from '@/uni_modules/mc-ui/libs/http/UniversalRequestQueue';
	const { request, requestByUrl, PromiseRequestByUrl, onAllComplete, onError } = useRequestQueue();
	import { useMainStore } from '@/store';
	const mainStore = useMainStore();
	// import nextTree from "@/commonPage/components/next-tree/components/next-tree/next-tree"


	// 是否展示搜索
	let showSearch = ref(false);

	// 接口请求关键字
	let searchKey = ref("");

	let filterResult = ref([]);
	let displayValue = ref("");
	let parentValue = ref("");


	let selectPickerSetting = reactive<any>(mainStore.SelectPickerSetting);
	let sql = selectPickerSetting.sql;
	let chooseType = selectPickerSetting.chooseType;
	showSearch.value = selectPickerSetting.showSearch;
	searchKey.value = selectPickerSetting.searchKey;
	displayValue.value = selectPickerSetting.displayValue;
	let hiddenValue = selectPickerSetting.hiddenValue;
	parentValue.value = selectPickerSetting.parentValue;
	// 查询条件数据
	let filterData = reactive(selectPickerSetting.param);
	// 页面传递的参数
	let pageParam = reactive(selectPickerSetting);
	let treeQuery = ref('1=1');
	let treeDataSource = ref(selectPickerSetting.treeObj.treeDataSource)
	let treeDisplayValue = ref(selectPickerSetting.treeObj.treeDisplayValue);
	let treeHiddenValue = ref(selectPickerSetting.treeObj.treeHiddenValue);
	let treeParentValues = ref(selectPickerSetting.treeObj.treeParentValues);
	let filterSQL = selectPickerSetting.filterSQL;
	let formSQL = selectPickerSetting.formSQL;

	function ChoiceCell(data : any) {
		//判断是否是单选
		if (chooseType == 1) {
			uni.$emit(pickerListen.value, {
				colName: pageParam.colName,
				msg: '',
				data: data
			});
			uni.navigateBack();
		}
	}


	function search() {
		paging.value.reload();
	}
	function SearchOrAdd() {

	};

	// 是否允许新增编辑
	let AllowAddEdit = ref(false);

	let nextTreeAsyncRef = ref<any>(null)
	function openChooseType() {
		nextTreeAsyncRef.value.showTree = true;
	}

	let typeName = ref("分类筛选")

	const paging = ref<any>(null);
	// 获取列表数据
	function getSearchList(pageNo : number, pageSize : number) {
		uni.$utils.showLoading("正在加载...");
		let filterQuerySql = ref(" and 1=1 ");
		if (formSQL) {
			filterQuerySql.value += " and " + formSQL;
		}
		let param_sql = ref("")
		if (sql.toLowerCase().indexOf('row_number') < 0) {
			param_sql.value = "select top " + pageSize + " * from ( SELECT row_number() over(  order by " +
				hiddenValue + " ) as _rownumber ,* FROM (" + sql + ")t where " + searchKey.value +
				" like '%" + filterData[searchKey.value] + "%' and " + treeQuery.value + filterQuerySql.value +
				" ) A where _rownumber > " + ((pageNo - 1) * pageSize)
					.toString() + "";



			param_sql.value += " select count(1) as count FROM (" + sql + ")t where " + searchKey.value +
				" like '%" + filterData[searchKey.value] + "%' and " + treeQuery.value + filterQuerySql.value;
		} else {

			param_sql.value = "select * from (" + sql + ") t where " + searchKey.value + " like '%" + filterData[searchKey.value] + "%' and " + treeQuery.value + filterQuerySql.value + " ";
			param_sql.value += " select count(1) as count from (" + sql + ") t where " + searchKey.value + " like '%" +
				filterData[searchKey.value] + "%' and " + treeQuery.value + filterQuerySql;

		};

		let param_query = reactive({
			sql: param_sql.value
		})
		Object.assign(param_query, filterData)

		// console.log(param_query);
		requestByUrl({
			config: {
				baseURL: "/SQLData/QuerySql"
			},
			url: '',
			method: 'POST',
			data: param_query,
			success(ret : any) {
				// console.log(ret);
				if (ret.status == 200) {
					paging.value.completeByTotal(ret.data.ds, ret.data.ds1[0]["count"]);

				} else {

					paging.value.complete(false);
				}
			}

		})


	}


	let expandNodes = ref<any>([]);
	let treeData = ref([]);
	let treeThemeColor = ref('#51d0d0');
	function onTreeConfirm(list : any) {
		console.log(list);
		let selectList = list.map(function (item : any) {
			return item[treeHiddenValue.value];
		});
		let selectNameList = list.map(function (item : any) {
			return item[treeDisplayValue.value];
		});
		if (selectNameList.length > 0) {
			typeName.value = selectNameList.join(',');
		} else {
			typeName.value = "分类筛选";
		}
		if (selectList.length > 0) {
			treeQuery.value = parentValue.value + ' in ( ' + selectList.join(',') + ' )';
		} else {
			treeQuery.value = '1=1';
		}
		search();
	}
	let pickerListen = ref("");

	function getLeftInfo() {
		requestByUrl({
			config: {
				baseURL: "/SQLData/GetDataBySql"
			},
			url: '',
			method: 'POST',
			data: {
				sql: treeDataSource.value,
				sqlParam: {}
			},
			success(ret : any) {
				if (ret.status == 200) {
					let list = ref([]);
					list.value = ret.data.ds;
					list.value.map((item : any) => {
						return item.label = item[treeDisplayValue.value], item.id = item[treeHiddenValue.value]
					})

					expandNodes.value = list.value.map((item : any) => {
						return item.id
					})

					treeData.value = tranList(list.value, 0);

				}
			}

		})
	}

	const tranList = (list : any[], rootVal : number | string) => {
		let childItem = ref<any>([]);

		for (let i = 0; i < list.length; i++) {
			if (list[i][treeParentValues.value] === rootVal) {
				const childObj = {
					...list[i],
					children: tranList(list, list[i][treeHiddenValue.value])
				};
				childItem.value.push(childObj);
			}
		}

		return childItem.value;
	};

	onAllComplete(() => {
		console.log('所有请求已完成');
		uni.$utils.hideLoading();

	})

	onLoad((option : any) => {
		if (!uni.$utils.isEmpty(option)) {
			pickerListen.value = option.pickerListen
		};
		if (treeDataSource.value) {
			getLeftInfo();
		}
		getSearchList(1, 20)

	});
	onUnload(() => {
		mainStore.SelectPickerSetting = {};
	});
</script>

<style lang="scss">
	.page__content {
		display: flex;
		flex-direction: column;
		height: 100vh;
		background-color: #eeeeee;

		.SearchBox {
			background-color: #fff;
			background-color: #51d0d0;
			padding: 6px 10px;
		}

		.MainBox {
			flex: 1;
			overflow: auto;
		}
	}
</style>